<template>
  <div class="uploadBox">
    <form enctype="multipart/form-data" id="test" method="post">
      <div class="usernamebox">
        <input type="text" name="name" v-model="uploadName">
      </div>
      <ul class="clearfix imgUl">
        <li v-for="(item,index) in imgArr">
          <img :src="item.base64" alt="item.name">
          <span class="del" @click="del(index)">删除</span>
          <div class="progress" v-if="proShow">
            <div>{{per}}</div>
          </div>
        </li>
        <li class="op">
          <input type="file" class="file" name="files" multiple v-on:change="addPic()">
          <input type="button" class="add" value="+" v-on:click="toAdd()">
        </li>
      </ul>
    </form>
    <div>
      <input type="button" value="上传" class="btn btn-primary" v-on:click="upload()">
      <input type="button" value="继续添加" class="btn btn-default" v-on:click="addKeep()">
    </div>
  </div>
</template>

<style>
li {
  list-style: none;
}
.clearfix:after {
  content: "";
  display: block;
  height: 0;
  clear: both;
  visibility: hidden;
}
.clearfix {
  zoom: 1;
}
.uploadBox .progress {
  width: 100%;
  height: 20px;
  position: absolute;
  left: 0px;
  bottom: -20px;
  border-top: 1px solid grey;
  border-bottom: 1px solid grey;
  border-radius: 0px;
  text-align: center;
  /* background-color: blue; */
  /* background-size: 20% 100%; */
}
.imgUl {
  width: 100%;
  height: 350px;
  overflow-y: scroll;
  background-color: #fff;
  padding: 5px;
}
.uploadBox .progress div {
  width: 0%;
  height: 100%;
  background-color: green;
}
.uploadBox .del {
  display: inline-block;
  width: 50px;
  height: 30px;
  font-size: 16px;
  line-height: 30px;
  color: red;
  position: absolute;
  right: 10px;
  bottom: -7px;
}
.uploadBox {
  /* width:100%; */
  /* height: 350px; */
  padding: 5px;
  /* overflow-y: scroll; */
}
.uploadBox ul li {
  width: 150px;
  height: 150px;
  /* line-height: 150px; */
  float: left;
  border: 1px solid grey;
  vertical-align: middle;
  margin: 3px;
  padding: 10px 5px 0px;
  box-sizing: border-box;
  position: relative;
}
.op {
  /* position: relative; */
  padding: 0px !important;
}
.uploadBox ul li img {
  width: 100%;
  height: 80%;
}
.uploadBox .add {
  width: 150px;
  height: 150px;
  background: none;
  font-size: 126px;
  line-height: 135px;
  opacity: 0.5;
  position: relative;
  top: 0px;
  left: 0px;
}
.uploadBox .file {
  width: 100%;
  height: 100%;
  opacity: 0;
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 122;
}
</style>

<script>
export default {
  data() {
    return {
      uploadName:"",
      menuImgUrl: "",
      imgArr: [],
      filesVal: "",
      proShow: false,
      per: 0
    };
  },
  mounted() {},
  methods: {
    upload() {
      let that = this;
      let url = "http://127.0.0.1:8080/linkMan/linkman/uploadFile";
      let url2 = "http://127.0.0.1:8080/linkMan/linkman/upload";
      let count = 0;
      let files = $(".file")[0].files;
      // var fd = new FormData($("#test")[0]);
      // this.updateFun(url2, fd);
      for (let ui = files.length - 1; ui >= 0; ui--) {
        let formData = new FormData();
        formData.append("files", files[ui]);
        formData.append("name", this.uploadName);
        formData.append("level", 1);
        // formData.append("name", sessionStorage.getItem("username"));
        formData.append("tel",sessionStorage.getItem("tel"))
        // formData.append("tel", "15100000051");
        this.updateFun(url2, formData, ui);
      }
      function progressBar(evt) {
        var loaded = evt.loaded; //已经上传大小情况
        var tot = evt.total; //附件总大小
        var per = Math.floor((100 * loaded) / tot); //已经上传的百分比
        $.fn.progressInit.draw(per + "%"); //绘制经度条
        console.log("loaded :", loaded, " -tot: ", tot, " -per: ", per);
      }
    },
    updateFun(url, data, ui) {
      let that = this;
      $.ajax({
        url: url,
        type: "post",
        data: data,
        dataType: "json",
        contentType: false,
        processData: false,
        xhr: () => {
          //ajax进度条，直接拿过去就可以用
          let xhr = $.ajaxSettings.xhr();
          if (xhr.upload) {
            xhr.upload.addEventListener(
              "progress",
              e => {
                let loaded = e.loaded; //已经上传大小情况
                let tot = e.total; //附件总大小
                let per = Math.floor((100 * loaded) / tot); //已经上传的百分比
                let imgEl = $($(".progress>div")[ui]).css("width", per + "%");
                that.per = per;
                console.log(loaded, " : ", per, " : ", tot);
                if (per == "100") {
                  setTimeout(() => {
                    that.imgArr.splice(ui, 1);
                  }, 500);
                }
                // $(".progress-bar").css("width", per + "%"); //这里指的是进度条的宽度等于完成的百分比
                // $.fn.progressInit.draw(per + '%'); //绘制经度条
              },
              false
            );
            return xhr;
          }
        },
        success: data => {
          console.log("返回的数据：" + JSON.stringify(data));
          that.proShow = true;
          // files[i].remove();
          setTimeout(() => {
            that.imgArr.splice(ui, 1);
          }, 500);
        }
      });
    },
    del(index) {
      this.imgArr.splice(index, 1);
      // event.target.parentNode.remove();
      $(".file").val("");
    },
    // 初始化图片上传控件
    toAdd() {
      this.addPic();
    },
    addKeep() {
      this.addPic();
    },
    addPic() {
      this.readFile();
    },
    readFile() {
      let that = this;
      var fd = new FormData();
      var iLen = $(".file")[0].files.length;
      for (let i = 0; i < iLen; i++) {
        if (!$(".file")[0]["value"].match(/.jpg|.gif|.png|.jpeg|.bmp/i)) {
          //判断上传文件格式
          return alert("上传的图片格式不正确，请重新选择");
        }
        var reader = new FileReader();
        fd.append(i, $(".file")[0].files[i]);
        reader.readAsDataURL($(".file")[0].files[i]); //转成base64
        reader.fileName = $(".file")[0].files[i].name;

        reader.onload = function(e) {
          var imgMsg = {
            name: this.fileName, //获取文件名
            base64: this.result //reader.readAsDataURL方法执行完后，base64数据储存在reader.result里
          };
          that.imgArr.push(imgMsg);
        };
      }
    }
  }
};
</script>

